#!/usr/bin/env bash
set -e
set -u

TARGET=""
MODE="debug"
PROJECT_DIR="."

detect_default_target() {
  echo "正在检测 macOS 架构..."
  if [[ "$(uname)" == "Darwin" ]]; then
    ARCH=$(uname -m)
    if [[ "$ARCH" == "arm64" ]]; then
      echo "aarch64-apple-darwin"
    else
      echo "x86_64-apple-darwin"
    fi
  else
    echo ""
  fi
}

show_usage() {
  echo "用法: $0 [mac-arm|mac-x86|linux-x86|win-x86] [release] [--project /path/to/project]"
  echo "不传目标会自动检测 macOS 架构。"
  exit 1
}

# 解析参数
while [[ $# -gt 0 ]]; do
  case "$1" in
    mac-arm|mac-x86|linux-x86|win-x86)
      TARGET="$1"
      shift
      ;;
    release)
      MODE="release"
      shift
      ;;
    --project)
      PROJECT_DIR="$2"
      shift 2
      ;;
    *)
      echo "未知参数: $1"
      show_usage
      ;;
  esac
done

# 如果没指定 TARGET，自动检测
if [[ -z "$TARGET" ]]; then
  echo "未指定目标，正在自动检测..."
  TARGET=$(detect_default_target)
  echo "检测到的目标: $TARGET"
  if [[ -z "$TARGET" ]]; then
    echo "无法自动检测目标，请手动指定。"
    show_usage
  fi
fi

# 映射 TARGET 到 Rust triple
case "$TARGET" in
  mac-arm)  TARGET_TRIPLE="aarch64-apple-darwin" ;;
  mac-x86)  TARGET_TRIPLE="x86_64-apple-darwin" ;;
  linux-x86) TARGET_TRIPLE="x86_64-unknown-linux-gnu" ;;
  win-x86)  TARGET_TRIPLE="x86_64-pc-windows-gnu" ;;
esac

# 安装目标
if ! rustup target list | grep -q "${TARGET_TRIPLE} (installed)"; then
  echo "目标 ${TARGET_TRIPLE} 未安装，正在安装..."
  rustup target add $TARGET_TRIPLE
fi

# Windows 特殊配置
if [ "$TARGET_TRIPLE" = "x86_64-pc-windows-gnu" ]; then
  if ! command -v x86_64-w64-mingw32-gcc &>/dev/null; then
    echo "⚠️  Windows 交叉编译需要 MinGW-w64 工具链，正在安装..."
    brew install mingw-w64
  fi
  export RUSTFLAGS=""
fi

# 开始编译
echo "🚀 编译项目: $PROJECT_DIR"
echo "目标: $TARGET_TRIPLE [$MODE]"

if [ "$MODE" = "release" ]; then
  cargo build --manifest-path "$PROJECT_DIR/Cargo.toml" --target $TARGET_TRIPLE --release -j $(sysctl -n hw.logicalcpu)
else
  cargo build --manifest-path "$PROJECT_DIR/Cargo.toml" --target $TARGET_TRIPLE -j $(sysctl -n hw.logicalcpu)
fi

echo "✅ 编译完成: $PROJECT_DIR/target/$TARGET_TRIPLE/$MODE/"
